(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('apf.finance.dueDateInvoiceListController', createController);
	createController.$inject = [ '$scope', 'Constants', 'arithService', 'modalService', 'gridService', 'layoutConfig', 'validatorConfig', 'authService',
			'piDiscountService' ];
	function createController($scope, Constants, arithService, modalService, gridService, layoutConfig, validatorConfig, authService, piDiscountService) {
		var ctrl = this, piDiscountRequestInfo = $scope.$stateParams.params, errorMessage = {};
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.piDiscountRequest = {};
		ctrl.amtChangedInv = {};
		ctrl.financeAmtByDate = {};
		
		ctrl.init = function() {
			ctrl.piDiscountRequest = piDiscountRequestInfo;
			ctrl.dateDisabled = piDiscountService.dateDisabled;
			ctrl.gridOptions = gridService.createGridOptions($scope, ctrl.layoutConfig.tableConfigs.table, paginationChanged, rowSelectionChanged, sortChanged);
			ctrl.gridOptions.data = 'vm.dueDateInvCriteria.list';
			ctrl.gridOptions.multiSelect = true;
			piDiscountRequestInfo.dueDateInvCriteria = ctrl.gridOptions.defaultSearchCriteria;
			piDiscountRequestInfo.dueDateInvCriteria.storageSearchCriteria = false;
			ctrl.dueDateInvCriteria = ctrl.gridOptions.defaultSearchCriteria;
			ctrl.dueDateInvCriteria.storageSearchCriteria = false;
		    authService.dueDateInvoiceList(ctrl.dueDateInvCriteria).then(function(response) {
			piDiscountService.getCurrencyOptions().then(function(currencyResponse) {
				ctrl.invoiceCcyOptions = currencyResponse.data;
				ctrl.invoiceCcyChanged = function(value, formCtrl, isInitialized){
					if(!isInitialized){
						ctrl.dueDateInvCriteria.invoiceCcy = value.invoiceCcy;
						ctrl.search();
					}
				};
				ctrl.effectiveDateChanged =function(value, formCtrl, isInitialized){
					if(!isInitialized){
						ctrl.dueDateInvCriteria.effectiveDate = value.effectiveDate;
						ctrl.search();
					}
				};
				if (response.data && response.data.model) {
					var dueDateInvCriteria = response.data.model.dueDateInvCriteria;
					angular.merge(ctrl.dueDateInvCriteria, dueDateInvCriteria);
					//change finance Amt
					angular.forEach(ctrl.dueDateInvCriteria.list, function(data) {
						if(ctrl.financeAmtByDate.hasOwnProperty(data.invoiceMaturitydate)){
							data.financeAmt = ctrl.financeAmtByDate[data.invoiceMaturitydate];
						}
					});
					ctrl.piDiscountRequest = response.data.model;
					ctrl.piDiscountRequest.availableAmount = dueDateInvCriteria.availableAmount;
					gridService.updateGridOptions(ctrl.dueDateInvCriteria, ctrl.gridOptions);
				}
			});
		  });
		};
		
		
		function btnCallbackOk(params){
			for(var invoiceId in params){
				var financeAmt = params[invoiceId];
				ctrl.amtChangedInv[invoiceId] = financeAmt;
			};
		};
		
		ctrl.openInvList = function(value){
			modalService.openCustomDialogs({
				'dialogsModule' : 'apf.partial.InvList',
				'size' : [1000,500],
				'btnCallback' :{
					'ok' : btnCallbackOk
				},
				'params' : {
					"row" : value,
					"financeAmtByDate" : ctrl.financeAmtByDate,
					"amtChangedInv" : ctrl.amtChangedInv,
					"effectiveDate" : ctrl.dueDateInvCriteria.effectiveDate,
					"invoiceCcy" : ctrl.dueDateInvCriteria.invoiceCcy,
					"isFinanceAmtReadOnly" : ctrl.dueDateInvCriteria.isFinanceAmtReadOnly,
					"partialFinanceOption" : ctrl.dueDateInvCriteria.partialFinanceOption
				}
			});
		};
		
		ctrl.search = function() {
			ctrl.dueDateInvCriteria.list = [];
			authService.dueDateInvoiceList(ctrl.dueDateInvCriteria).then(
			function(response) {
				var dueDateInvCriteria = response.data.model.dueDateInvCriteria;
				angular.merge(ctrl.dueDateInvCriteria, dueDateInvCriteria);
				//change finance Amt
				angular.forEach(ctrl.dueDateInvCriteria.list, function(data) {
					if(ctrl.financeAmtByDate.hasOwnProperty(data.invoiceMaturitydate)){
						data.financeAmt = ctrl.financeAmtByDate[data.invoiceMaturitydate];
					}
				});
				ctrl.piDiscountRequest.invoiceCcy = dueDateInvCriteria.invoiceCcy;
				ctrl.piDiscountRequest.availableAmount = dueDateInvCriteria.availableAmount;
				ctrl.piDiscountRequest.partialFinanceOption = dueDateInvCriteria.partialFinanceOption;
				ctrl.piDiscountRequest.financeBy = response.data.model.financeBy;
				if(ctrl.piDiscountRequest.effectiveDate > $scope.site.bizDate){
					ctrl.piDiscountRequest.isFutureDate = true;
				}else{
					ctrl.piDiscountRequest.isFutureDate = false;
				}
				gridService.updateGridOptions(ctrl.dueDateInvCriteria, ctrl.gridOptions);
			},angular.noop);
		};

		function paginationChanged(pageNum, pageSize) {
			ctrl.dueDateInvCriteria.pageNum = pageNum;
			ctrl.dueDateInvCriteria.pageSize = pageSize;
			ctrl.dueDateInvCriteria.list = [];
			ctrl.search();
		}

		ctrl.createContinue = function() {
			if (!ctrl.selectedRows || ctrl.selectedRows.length == 0) {
				modalService.openErrorDialogs({
					messages : [ 'title.dialogs.info.norecsel' ]
				});
				return;
			}
			ctrl.piDiscountRequest.invoiceMaturitydates = [];
			ctrl.piDiscountRequest.discountInvoiceList = [];
			ctrl.piDiscountRequest.amtChangedInv = ctrl.amtChangedInv;
			angular.forEach(ctrl.selectedRows, function(invoice, index) {
				var invoiceMaturitydate = invoice.invoiceMaturitydate;
				ctrl.piDiscountRequest.invoiceMaturitydates.push(invoiceMaturitydate);
			});
			if(ctrl.piDiscountRequest.isFutureDate){
				return authService.createContinue(ctrl.piDiscountRequest).then(successful, failed);
			}else{
				return authService.createPreview(ctrl.piDiscountRequest).then(successful, failed);
			}
		};

		function failed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}
		
		function successful(response) {
			if (response.data && response.data.model) {
				var piDiscountRequest = response.data.model;
				piDiscountRequest.invoiceMaturitydates = ctrl.piDiscountRequest.invoiceMaturitydates
			}
			var params = {
					'selectedRows' : ctrl.selectedRows,
					'amtChangedInv' : ctrl.amtChangedInv,
					'piDiscountRequest' : piDiscountRequest,
					'financeBy' : ctrl.piDiscountRequest.financeBy
			};
			if(ctrl.piDiscountRequest.isFutureDate){
				$scope.go('apf.finance.create', params);
			}else{
				$scope.go('apf.finance.preview',params);
			}
		}
		function sortChanged(sortColumns) {
			// now just support sort by one column
			ctrl.dueDateInvCriteria.sortDirection = sortColumns[0] ? sortColumns[0].direction : '';
			ctrl.dueDateInvCriteria.sortBy = sortColumns[0] ? sortColumns[0].sortBy : '';
			ctrl.search();
		}
		
		function rowSelectionChanged(eventRow, selectedRows) {
			ctrl.selectedRows = selectedRows;
		}
	}
})(angular);